package com.dek.ssm.ch19.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.SessionCallback;
import org.springframework.stereotype.Service;

import com.dek.ssm.ch19.RedisTemplateService;

@Service
public class RedisTemplateServiceImpl implements RedisTemplateService {
	
	@Autowired
	private RedisTemplate redisTemplate;
	
	
	@Override
	public void execMultiCommand() {
		Object o = redisTemplate.execute((RedisOperations ops) -> {
			ops.boundValueOps("key1").set("value1");
			ops.boundHashOps("hash").put("hash-key-1", "hash-value-1");
			return ops.boundValueOps("key1").get();
		});
		System.out.println(o);
	}

	@Override
	public void execTransaction() {
		List list= (List) redisTemplate.execute( (RedisOperations ops ) -> {
			ops.watch("key1");
			//开启事务
			ops .multi() ;
			//注意，命令都不会被马上执行，只会放到 Redis 的队列中，只会返回为 null
			ops.boundValueOps (" key l ") . set ("abc");
			ops.boundHashOps (" hash" ) .put ("hash-ke y-1","hash-value- 1");
			ops . opsForValue() . get (" keyl ");
			//执行 exec 方法后会触发事务执行，返回结果，存放到 list 中
			List result = ops . exec() ;
			return result;
		});
	}

	@Override
	public void execPipeline() {
		List list = redisTemplate. executePipelined ( new SessionCallback () {
			@Override
			public Object execute(RedisOperations operations) throws DataAccessException {
				//在流水线下，命令不会马上返回结果，结果是一次性执行后返回的
				operations.opsForValue().set (" keyl","valuel ");
				operations.opsForHash().put ("hash"," key-hash-1","value-hash-1");
				operations.opsForValue().get (" keyl ");
				return null;
			}
			
		});
	}

}
